﻿using System;

namespace Sustainalytics.Entities.ProductInvolvement
{
    public class PIRange
    {
        public virtual int RangeId { get; set; }
        public bool NA { get; set; }
        public virtual double Start { get; set; }
        public virtual double Stop { get; set; }
        public virtual int Score { get; set; }

        public static PIRange FromString(int number, string s /* x-y%  or n/a */)
        {
            //50-100%
            var result = new PIRange() { RangeId = number, Start = -1, Stop = -1 };
            if (s.Contains("%"))
            {
                var vals = s.Split(new char[] { '%', '-' }, StringSplitOptions.RemoveEmptyEntries);
                if (vals.Length == 2)
                {
                    double first;
                    double second;
                    if (double.TryParse(vals[0], out first) && double.TryParse(vals[1], out second))
                    {
                        result.Start = first;
                        //Mihai - is it also needed for 100%?
                        result.Stop = !second.Equals(100) ? second - .01 : second;
                    }
                }
            }
            else if (s.ToLowerInvariant().Contains("n/a") || string.IsNullOrEmpty(s))
            {
                result.NA = true;
            }

            return result;
        }

        public static PIRange FromRangeAndScore(int number, string range, string score)
        {
            var result = FromString(number, range);
                    
            result.Score = score.ParseOrDefault(int.TryParse, -1);

            return result;
        }
    }
}
